package com.lenovo.lcdm.dcm.config.login;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.jwt.BadJwtException;
import org.springframework.security.oauth2.jwt.JwtValidationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;
import java.io.PrintWriter;


/**
 * 认证失败返回结果处理
 *
 * @author lihc14
 */
@Slf4j
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        if (response.isCommitted()) {
            return;
        }

        Throwable throwable = authException.fillInStackTrace();
        String errorMessage = "登录失败";
        if (throwable instanceof BadCredentialsException) {
            errorMessage = throwable.getMessage();
        } else {
            Throwable cause = authException.getCause();
            if (cause instanceof JwtValidationException) {
                log.warn("JWT Token 过期，具体内容:" + cause.getMessage());
                errorMessage = throwable.getMessage();
            } else if (cause instanceof BadJwtException) {
                log.warn("JWT 签名异常，具体内容：" + cause.getMessage());
                errorMessage = throwable.getMessage();
            } else if (cause instanceof AccountExpiredException) {
                errorMessage = throwable.getMessage();
            } else if (cause instanceof LockedException) {
                errorMessage = throwable.getMessage();
            } else if (throwable instanceof UsernameNotFoundException) {
                errorMessage = throwable.getMessage();
            } else if (throwable instanceof InsufficientAuthenticationException) {
                errorMessage = throwable.getMessage();
            }
        }

        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        ObjectMapper objectMapper = new ObjectMapper();
        String resBody = objectMapper.writeValueAsString(errorMessage);
        PrintWriter printWriter = response.getWriter();
        printWriter.print(resBody);
        printWriter.flush();
        printWriter.close();
    }
}
